<!DOCTYPE html>
<html
  xmlns:th="http://www.thymeleaf.org"
  xmlns:sec="http://www.thymeleaf.org/extras/spring-security"
>
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>AI面试对话 - AI面试系统</title>
    <link
      href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css"
      rel="stylesheet"
    />
    <link
      rel="stylesheet"
      href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css"
    />
    <style>
      .chat-container {
        height: 70vh;
        overflow-y: auto;
        border: 1px solid #dee2e6;
        border-radius: 0.375rem;
        padding: 1rem;
        background-color: #f8f9fa;
      }
      .message {
        margin-bottom: 1rem;
        display: flex;
        align-items: flex-start;
      }
      .message.user {
        justify-content: flex-end;
      }
      .message.ai {
        justify-content: flex-start;
      }
      .message-content {
        max-width: 70%;
        padding: 0.75rem 1rem;
        border-radius: 1rem;
        word-wrap: break-word;
      }
      .message.user .message-content {
        background-color: #007bff;
        color: white;
      }
      .message.ai .message-content {
        background-color: white;
        border: 1px solid #dee2e6;
      }
      .message-avatar {
        width: 40px;
        height: 40px;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        margin: 0 0.5rem;
        font-size: 1.2rem;
      }
      .message.user .message-avatar {
        background-color: #007bff;
        color: white;
      }
      .message.ai .message-avatar {
        background-color: #28a745;
        color: white;
      }
      .typing-indicator {
        display: none;
        align-items: center;
        margin-bottom: 1rem;
      }
      .typing-dots {
        display: flex;
        gap: 0.25rem;
      }
      .typing-dots span {
        width: 8px;
        height: 8px;
        border-radius: 50%;
        background-color: #6c757d;
        animation: typing 1.4s infinite ease-in-out;
      }
      .typing-dots span:nth-child(1) {
        animation-delay: -0.32s;
      }
      .typing-dots span:nth-child(2) {
        animation-delay: -0.16s;
      }
      @keyframes typing {
        0%,
        80%,
        100% {
          transform: scale(0);
        }
        40% {
          transform: scale(1);
        }
      }
      .resume-summary {
        background-color: #e3f2fd;
        border-left: 4px solid #2196f3;
        padding: 1rem;
        margin-bottom: 1rem;
        border-radius: 0.375rem;
      }
    </style>
  </head>
  <body>
    <nav class="navbar navbar-expand-lg navbar-dark bg-primary">
      <div class="container">
        <a class="navbar-brand" href="#">AI面试系统</a>
        <button
          class="navbar-toggler"
          type="button"
          data-bs-toggle="collapse"
          data-bs-target="#navbarNav"
        >
          <span class="navbar-toggler-icon"></span>
        </button>
        <div class="collapse navbar-collapse" id="navbarNav">
          <ul class="navbar-nav ms-auto">
            <li class="nav-item">
              <span
                class="nav-link"
                th:text="${#authentication != null and #authentication.principal != null and #authentication.principal.username != null ? '欢迎，' + #authentication.principal.username : '欢迎，游客'}"
              ></span>
            </li>
            <li class="nav-item">
              <a class="nav-link" th:href="@{/interviews}">我的面试</a>
            </li>
            <li class="nav-item" sec:authorize="hasRole('ADMIN')">
              <a class="nav-link" th:href="@{/admin/users}">用户管理</a>
            </li>
            <li class="nav-item">
              <a class="nav-link" th:href="@{/logout}">退出登录</a>
            </li>
          </ul>
        </div>
      </div>
    </nav>

    <div class="container mt-4">
      <div class="row">
        <div class="col-12">
          <div class="card shadow">
            <div
              class="card-header bg-primary text-white d-flex justify-content-between align-items-center"
            >
              <h4 class="mb-0"><i class="bi bi-chat-dots"></i> AI面试对话</h4>
              <div>
                <span
                  class="badge bg-light text-dark"
                  th:text="${interview != null && interview.jobPosition != null ? '职位: ' + interview.jobPosition : '职位信息不可用'}"
                ></span>
                <span
                  class="badge bg-warning text-dark ms-2"
                  th:text="${interview != null ? '问题 ' + (interview.currentQuestionNumber != null ? interview.currentQuestionNumber : 1) + '/' + (interview.totalQuestions != null ? interview.totalQuestions : 5) : '问题信息不可用'}"
                ></span>
              </div>
            </div>
            <div class="card-body">
              <!-- 简历概括 -->
              <div
                th:if="${interview != null && interview.resumeSummary != null}"
                class="resume-summary"
              >
                <h6><i class="bi bi-file-text"></i> 简历概括</h6>
                <p th:text="${interview.resumeSummary}" class="mb-0"></p>
              </div>

              <!-- 聊天消息区域 -->
              <div id="chatContainer" class="chat-container">
                <!-- 消息将通过JavaScript动态添加 -->
              </div>

              <!-- 输入区域 -->
              <div class="mt-3">
                <div class="input-group">
                  <textarea
                    id="messageInput"
                    class="form-control"
                    rows="3"
                    placeholder="请输入您的回答..."
                    th:disabled="${interview != null && interview.status != null && interview.status.name() == 'COMPLETED'}"
                  ></textarea>
                  <button
                    id="sendButton"
                    class="btn btn-primary"
                    type="button"
                    th:disabled="${interview != null && interview.status != null && interview.status.name() == 'COMPLETED'}"
                  >
                    <i class="bi bi-send"></i> 发送
                  </button>
                </div>
                <div class="form-text">
                  <span
                    th:if="${interview != null && interview.status != null && interview.status.name() == 'IN_PROGRESS'}"
                  >
                    请回答AI的问题，回答完成后点击发送按钮
                  </span>
                  <span
                    th:if="${interview != null && interview.status != null && interview.status.name() == 'COMPLETED'}"
                    class="text-success"
                  >
                    <i class="bi bi-check-circle"></i> 面试已完成
                  </span>
                </div>
              </div>

              <!-- 操作按钮 -->
              <div class="mt-3 text-center">
                <a th:href="@{/interview}" class="btn btn-secondary me-2">
                  <i class="bi bi-arrow-left"></i> 返回
                </a>
                <a
                  th:if="${interview != null && interview.status != null && interview.status.name() == 'COMPLETED'}"
                  th:href="@{/result/{id}(id=${interview.id})}"
                  class="btn btn-success"
                >
                  <i class="bi bi-clipboard-check"></i> 查看结果
                </a>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 打字指示器 -->
    <div id="typingIndicator" class="typing-indicator">
      <div class="message-avatar">
        <i class="bi bi-robot"></i>
      </div>
      <div class="typing-dots">
        <span></span>
        <span></span>
        <span></span>
      </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.bundle.min.js"></script>
    <script th:inline="javascript">
      const interviewId =
        /*[[${interview != null && interview.id != null ? interview.id : null}]]*/ null;
      const chatContainer = document.getElementById("chatContainer");
      const messageInput = document.getElementById("messageInput");
      const sendButton = document.getElementById("sendButton");
      const typingIndicator = document.getElementById("typingIndicator");

      // 调试信息
      console.log("Interview ID:", interviewId);
      // 仅输出ID，避免在模板中内联复杂对象
      console.log("Interview object present:", interviewId !== null);

      // 检查interviewId是否有效
      if (!interviewId) {
        console.error("Interview ID is null or undefined!");
        document.body.innerHTML =
          '<div class="container mt-5"><div class="alert alert-danger">错误：面试ID无效，请重新开始面试。</div><a href="/interview" class="btn btn-primary">返回面试页面</a></div>';
      }

      // 页面加载时获取聊天历史
      document.addEventListener("DOMContentLoaded", function () {
        loadChatHistory();
      });

      // 发送消息
      sendButton.addEventListener("click", sendMessage);
      messageInput.addEventListener("keypress", function (e) {
        if (e.key === "Enter" && !e.shiftKey) {
          e.preventDefault();
          sendMessage();
        }
      });

      function sendMessage() {
        const message = messageInput.value.trim();
        if (!message) return;

        // 检查interviewId是否存在
        if (!interviewId) {
          console.error("Interview ID is null or undefined");
          addMessage(
            "ai",
            "错误：面试ID不存在，请重新开始面试。如果问题持续存在，请联系管理员。"
          );
          return;
        }

        // 添加用户消息到聊天界面
        addMessage("user", message);
        messageInput.value = "";

        // 显示打字指示器
        showTypingIndicator();

        // 发送到服务器
        fetch("/api/chat/send", {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify({
            interviewId: interviewId,
            message: message,
          }),
        })
          .then((response) => response.json())
          .then((data) => {
            hideTypingIndicator();
            if (data.success) {
              if (data.aiResponse) {
                addMessage("ai", data.aiResponse);
              }
              if (data.interviewCompleted) {
                // 面试完成，重定向到结果页面
                setTimeout(() => {
                  window.location.href = "/result/" + interviewId;
                }, 2000);
              }
            } else {
              addMessage("ai", "抱歉，发生了错误：" + data.error);
            }
          })
          .catch((error) => {
            hideTypingIndicator();
            addMessage("ai", "抱歉，网络连接出现问题，请稍后重试。");
            console.error("Error:", error);
          });
      }

      // 修复后的完整 addMessage 函数
      function addMessage(sender, content) {
        const messageDiv = document.createElement("div");
        messageDiv.className = `message ${sender}`;

        const avatarDiv = document.createElement("div");
        avatarDiv.className = "message-avatar";
        avatarDiv.innerHTML =
          sender === "user"
            ? '<i class="bi bi-person"></i>'
            : '<i class="bi bi-robot"></i>';

        const contentDiv = document.createElement("div");
        contentDiv.className = "message-content";
        contentDiv.textContent = content;

        messageDiv.appendChild(avatarDiv);
        messageDiv.appendChild(contentDiv);

        chatContainer.appendChild(messageDiv);

        // 滚动到底部
        chatContainer.scrollTop = chatContainer.scrollHeight;
      }

      function showTypingIndicator() {
        typingIndicator.style.display = "flex";
        chatContainer.appendChild(typingIndicator);
        chatContainer.scrollTop = chatContainer.scrollHeight;
      }

      function hideTypingIndicator() {
        typingIndicator.style.display = "none";
      }

      function loadChatHistory() {
        if (!interviewId) return;

        fetch("/api/chat/history/" + interviewId)
          .then((response) => response.json())
          .then((data) => {
            if (data.success && data.messages) {
              data.messages.forEach((msg) => {
                addMessage(msg.sender, msg.content);
              });
            }
          })
          .catch((error) => {
            console.error("Failed to load chat history:", error);
            addMessage("ai", "加载聊天历史失败，请刷新页面重试。");
          });
      }
    </script>
  </body>
</html>
